const puppeteer = require('puppeteer')
const inquirer = require('inquirer')
const url = `https://www.javlands.net/tw/`
const func = async () => {
    console.log(`初始化运行环境.....`)
    // 开启浏览器
    const browser = await puppeteer.launch({ headless: true })
    // 开启一个新页面
    const page = await browser.newPage()
    // 打开URL
    await page.goto(url, {
        waitUntil: 'domcontentloaded'
    })

    const searchDVD_ID = async (DVD_ID) => {
        try {
            // 模拟真实输入
            await page.type('input.form-control', DVD_ID, { delay: 100 });
            // 点击此节点
            await page.click('button.form-control');
            // 等待页面加载
            await page.waitForTimeout(2000);
            // 获取标题
            const result = await page.evaluate(() => {
                const title = document.querySelector('.k-right .container-fluid strong')
                if (!title) return {
                    status: 0,
                    msg: "\n网络波动，请重试。"
                }
                const notFound = document.querySelector('.k-right .container-fluid .row .text-center')
                if (notFound) return {
                    status: 0,
                    msg: `\n未找到该番号的相关信息。`
                }
                return {
                    status: 1,
                    msg: `\n\n${title.textContent.trim()}\n`
                }
            })
            return result
        } catch (error) {
            console.log(error);
            browser.close();
            process.exit(0)
        }
    }
    const question = [{
        type: 'input',
        name: 'DVD_ID',
        message: '请输入番号',
        validate: async function (input) {
            if (['q', 'Q', ''].includes(input)) {
                browser.close()
                process.exit(0)
            }
            const { status, msg } = await searchDVD_ID(input)
            console.log(msg)
            return !!status
        }
    }]

    const ask = async () => {
        await inquirer.prompt(question)
        ask()
    }

    ask()
}

func()